package com.ibo.demo.upnp.adapter;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.ibo.demo.upnp.R;

import org.fourthline.cling.model.meta.Device;

import java.util.List;

public class DeviceListAdapter extends RecyclerView.Adapter<DeviceListAdapter.MyHolder> {

    private List<Device> deviceList;
    private DeviceClickListener listener;

    public DeviceListAdapter(List<Device> deviceList) {
        this.deviceList = deviceList;
    }

    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new MyHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.device_item, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull MyHolder holder, int position) {
        holder.tv.setText(deviceList.get(position).getDetails().getFriendlyName());
    }

    @Override
    public int getItemCount() {
        return deviceList.size();
    }

    class MyHolder extends RecyclerView.ViewHolder {

        private final TextView tv;

        public MyHolder(View itemView) {
            super(itemView);
            tv = ((TextView) itemView.findViewById(R.id.name));
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.onDeviceSelected(deviceList.get(getAdapterPosition()));
                    }
                }
            });
        }
    }

    public interface DeviceClickListener {
        void onDeviceSelected(Device device);
    }

    public void setDeviceListener(DeviceClickListener listener) {

        this.listener = listener;
    }

}
